const baseUrl = `${window.location.origin}/`;
var a = 0;
//itemList初始数据
var itemData = [];
var i = 0;
//判断新增还是编辑：0为新增，1为编辑
var editIndex = 0;
//itemTable被选中的项目
var itemTableData = [];
//存放itemList被选中的项目
var itemListData;
//编辑时被移除的项目
var deleteItemId = [];
var b = 0;
var index;
var options = {typeNumber:4,errorCorrectLevel:'M',size:200};
layui.use(['element','form','table','layer','laydate'], function () {
    var element = layui.element;
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var laydate = layui.laydate;
    $ = layui.jquery;

    //执行一个laydate实例
    laydate.render({
        elem: '#beginDate' //指定元素
        ,type: 'datetime'
    });
    laydate.render({
        elem: '#endDate' //指定元素
        ,type: 'datetime'
    });

    table.render({
        elem: '#pointTable'
        ,cellMinWidth: 80
        ,method: 'post'
        ,url: baseUrl+'/eleinspect/point/getPointTable'
        ,title: '点位管理表'
        ,toolbar: '#toolbarDemo' //开启头部工具栏
        ,page: true
        ,cols: [[
            {type: 'checkbox', fixed: 'left'}
            ,{type:'numbers',title:'序号'}
            ,{field:'pointName', title:'点位名称', align:'center'}
            ,{field:'pointDetail', title:'点位描述', align:'center'}
            ,{field:'pointCreateTime', title:'创建时间', align:'center'}
            ,{field:'pointSystemInfo', title:'二维码信息',align:'center', templet:function(d){
                var twoImg = drawImg(d.pointSystemInfo,options);
                return '<img style="cursor: pointer" onclick="magnifyPic(this)" title="'+d.pointName+'" width="30" height="30" src="'+twoImg+'">';
            }}
            ,{field:'right', title:'操作', align:'center',templet:
                    function (data) {
                        return '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a><a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="detail">查看</a><a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>'
                    }}
        ]]
    });

    table.render({
        elem: '#itemTable'
        ,cellMinWidth: 80
        ,method: 'post'
        ,url: baseUrl+'/eleinspect/point/getItemTable'
        ,title: '项目管理表'
        ,page: true
        ,cols: [[
            {type: 'checkbox', fixed: 'left'}
            ,{type:'numbers',title:'序号'}
            ,{field:'itemsName', title:'项目名称'}
            ,{field:'itemsDetail', title:'项目备注'}
        ]]
    });

    table.render({
        elem: '#itemList'
        ,data: itemData
        ,cellMinWidth: 80
        ,method: 'post'
        ,title: '项目表'
        ,page: true
        ,cols: [[
            {type:'numbers',title:'序号'}
            ,{field:'itemsName', title:'项目名称'}
            ,{field:'itemsDetail', title:'项目备注'}
            ,{field:'right', title:'操作',templet:
                    function (data) {
                        return '<a class="layui-btn layui-btn-xs" lay-event="deleteItem">移除</a>'
                    }}
        ]]
        ,done:function (res,curr,count) {
            itemListData = res;
        }
    });


    table.on('tool(pointTable)',function (obj) {
        var rowData = obj.data;
        if (obj.event === 'edit') {
            $("#toAddItem").css('display','');
            $("#addBtn").css('display','');
            itemTableData = [];
            i = 0;
            //初始化
            $.ajax({
                url: baseUrl+"/eleinspect/point/getPointItemInfo",
                type: 'post',
                data: {
                    mappingPointId: rowData.pointId
                },
                success:function(res){
                    for (i = 0;i < res.data.length;i++) {
                        // itemTableData[i] = res.data[i];
                        itemTableData.push(res.data[i]);
                    }
                    table.reload('itemList',{
                        data: res.data
                    },'data')
                }
            });
            deleteItemId = [];
            b = 0;
            editIndex = 1;
            $("#pointId").val(rowData.pointId);
            $("#pointName").val(rowData.pointName);
            $("#pointDetail").val(rowData.pointDetail);
            $("#pointInspectMethod").val(rowData.pointInspectMethod);
            $("#pointSystemInfo").val(rowData.pointSystemInfo);
            var twoCode = drawImg(rowData.pointSystemInfo,options);
            $("#twoDemPic").attr("src",twoCode);
            // $("#pointInspectTime").val(rowData.pointInspectTime);
            // $("#pointInspectErrorTime").val(rowData.pointInspectErrorTime);
            $("#itemsName").val(rowData.itemsName);
            form.render();
            layer.open({
                type: 1,
                title:"编辑",
                offset: 'auto',
                skin:'demo-class',
                closeBtn: 1,
                shift: 2,
                area: ['80%', '100%'],
                shadeClose: true,
                content: $("#point_main"),
                skin: 'to-fix-select'
            });
        }else if(obj.event === 'detail'){
            //初始化
            $.ajax({
                url: baseUrl+"/eleinspect/point/getPointItemInfo",
                type: 'post',
                data: {
                    mappingPointId: rowData.pointId
                },
                success:function(res){
                    table.reload('itemList',{
                        data: res.data
                    },'data')
                }
            });
            //表单填充
            $("#pointId").val(rowData.pointId);
            $("#pointName").val(rowData.pointName);
            $("#pointDetail").val(rowData.pointDetail);
            $("#pointInspectMethod").val(rowData.pointInspectMethod);
            $("#pointSystemInfo").val(rowData.pointSystemInfo);
            var twoCode = drawImg(rowData.pointSystemInfo,options);
            $("#twoDemPic").attr("src",twoCode);
            // $("#pointInspectTime").val(rowData.pointInspectTime);
            // $("#pointInspectErrorTime").val(rowData.pointInspectErrorTime);
            $("#itemsName").val(rowData.itemsName);
            $("#toAddItem").css('display','none');
            $("#addBtn").css('display','none');
            deletePointId = [];
            b = 0;
            editIndex = 1;
            form.render();
            layer.open({
                type: 1,
                title:"查看",
                offset: 'auto',
                skin:'demo-class',
                closeBtn: 1,
                shift: 2,
                area: ['80%', '100%'],
                shadeClose: true,
                content: $("#point_main"),
                skin: 'to-fix-select'
            });
        }else if(obj.event === 'delete'){
            console.log(rowData.pointId);
            layer.confirm('确定删除?',{btn:['确定','返回']},function (index) {
                $.ajax({
                    url: baseUrl+"/eleinspect/point/deletePoint",
                    type:'post',
                    data:{
                        pointId:rowData.pointId
                    },
                    success:function(data){
                        if (data.code == 0) {
                            layer.msg(data.msg,{icon:1});
                        }else{
                            layer.alert(data.msg,{icon:2});
                        }
                        active['reload'].call(this);
                    }
                });
            });
        }
    });

    $('#toAdd').on('click',function () {
        //初始化
        $("#toAddItem").css('display','');
        $("#addBtn").css('display','');
        $("#pointId").val("");
        $("#pointName").val("");
        $("#pointDetail").val("");
        $("#pointInspectMethod").val("");
        $("#pointSystemInfo").val("");
        $("#pointInspectTime").val("");
        $("#pointInspectErrorTime").val("");
        $("#itemsName").val("");
        form.render();
        itemData = [];
        deletePointId = [];
        b = 0;
        editIndex = 0;
        itemTableData = [];
        i = 0;
        table.reload('itemList',{
            data: itemData
        },'data');

        layer.open({
            type: 1,
            title:"新增",
            offset: 'auto',
            skin:'demo-class',
            closeBtn: 1,
            shift: 2,
            area: ['80%', '100%'],
            shadeClose: true,
            content: $("#point_main"),
            skin: 'to-fix-select',
        });
    });

    form.on('submit(search)',function (data) {
        var searchText = $('#searchText').val();
        table.reload('pointTable', {
            page: {
                curr: 1
            },
            where: {
                pointName: searchText.trim(),
                beginDate: $("#beginDate").val(),
                endDate: $("#endDate").val()
            }
        }, 'data');
        return false;
    });

    //增加项目
    $("#toAddItem").on('click',function () {
        //初始化
        a = 0;
        // itemTableData = [];
        i = 0;
        table.reload('itemTable', {});
        index = layer.open({
            type: 1,
            title:"增加项目",
            offset: 'auto',
            skin:'demo-class',
            closeBtn: 1,
            shift: 2,
            area: ['60%', '80%'],
            shadeClose: true,
            content: $("#item_main"),
            skin: 'to-fix-select'
        });
    });

    function hasTheData(data,id){
        if(!data){
            return false;
        }
        for (var i = 0; i < data.length; i++) {
            if(data[i].itemsId === id){
                return true;
            }
        }
        return false;
    }

    var checkboxClicked = false; // 是否点击选择过checkbox
    //itemTable中被选中的项目
    table.on('checkbox(itemTable)',function (obj) {
        if(obj.type === "one") { //单选操作
            if (obj.checked == true){
                checkboxClicked = true;
                var flag = hasTheData(itemTableData,obj.data.itemsId);
                if(!flag){
                    itemTableData.push(obj.data);
                }
                i++;
            }else {
                if(checkboxClicked){
                    deleteById(obj.data.itemsId);
                }
            }
        }
        // else{
        //     for (var j=0; j < itemTableData.length; j++){
        //         if(itemTableData[j] != null && itemTableData[j].itemsId == obj.data.itemsId){
        //             itemTableData.splice(j,1);
        //         }else{
        //             continue;
        //         }
        //         console.log("删除length" + itemTableData.length);
        //         console.log("删除" + itemTableData);
        //     }
        // }
        itemTableData = itemTableData.filter(function (value) {
            return value && value.toString().trim();
        });
    });

    function deleteById(id){
        for (var j=0; j < itemTableData.length; j++){
            if(itemTableData[j] != null && itemTableData[j].itemsId === id){
                itemTableData.splice(j,1);
            }
        }
    }

    //itemTable中被选中的项目移动到itemList
    $("#addItem").on('click',function () {
        if(table.checkStatus('itemTable').isAll){
            table.reload('itemList',{
                data: table.checkStatus('itemTable').data
            },'data');
            layer.close(index);
        }else{
            table.reload('itemList',{
                data: itemTableData
            },'data');
            layer.close(index);
        }
    });

    //移除itemList中的项目
    table.on('tool(itemList)',function (obj) {
        if (obj.event === 'deleteItem'){
            deleteItemId[b] = obj.data.itemsId;
            b++;
            obj.del();
        }
    });

    form.on("submit(addBtn)",function (data) {
        var pointSystemInfo = $("#pointSystemInfo").val();
        if(!pointSystemInfo){
            layer.msg("请先生成二维码",{icon:5});
            return false;
        }
        var dataArray = itemListData.data;
        var dataArrayJson = JSON.stringify(dataArray);
        var deleteItemIdJson = JSON.stringify(deleteItemId);
        if(dataArray.length === 0){
            layer.msg("请添加项目",{icon:5});
            return false;
        }
        layer.confirm('是否确认提交？',{btn: ['确定','返回']},function (index) {
            $.ajax({
                url: baseUrl+"/eleinspect/point/savePointInfo",
                type: 'post',
                data: {
                    pointId: $("#pointId").val(),
                    pointName: $("#pointName").val(),
                    pointDetail: $("#pointDetail").val(),
                    pointInspectMethod: 0,
                    pointSystemInfo: $("#pointSystemInfo").val(),
                    //pointInspectTime: $("#pointInspectTime").val(),
                    //pointInspectErrorTime: $("#pointInspectErrorTime").val(),
                    dataArrayJson: dataArrayJson,
                    editIndex: editIndex,
                    deleteItemIdJson: deleteItemIdJson
                },
                success:function(data){
                    if (data.code == 0) {
                        layer.closeAll();
                        layer.msg(data.msg,{icon:1});
                        //执行重载
                        table.reload('pointTable', {});
                    }else{
                        layer.alert(data.msg,{icon:2});
                        table.reload('itemList', {});
                    }
                }
            });
        });
        return false;
    });

    active = {
        reload: function(){
            //执行重载
            table.reload('pointTable', {

            });
        }
    }
    $("#generateUUID").on('click',function (){
        var uuid = generateUUID();
        var twoCode = drawImg(uuid,options);
        $("#twoDemPic").attr("src",twoCode);
        $("#pointSystemInfo").val(uuid);
    });

});

function reload(){
    $("#searchText").val("");//火狐需要
    $("#beginDate").val("");
    $("#endDate").val("");
    location.reload();
}
function generateUUID() {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}
function magnifyPic(ele) {
    var bigH = 500;
    var bigW = 500;
    // 放大预览图片
    layer.open({
        type: 1,
        title: false,
        closeBtn: 1,
        shadeClose: true,
        area: ['560px', '560px'], //宽高
        content: "<button class='layui-btn' onclick='printfun()'>打印</button>" +
            "<!--startprint--><img width='"+bigW+"' height='"+bigH+"' src=" + $(ele).attr("src") + " /><div id='printImg'><label style='margin-left: 200px;font-size: medium'>点位名称:</label><label style='font-size: medium;font-weight: bold'>"+$(ele).attr("title")+"</label></div><!--endprint-->"});
}
function printfun(){
    // var bdhtml1 = document.body.innerHTML;
    // var bdhtml=bdhtml1; //获取当前页的html代码
    // var sprnstr="<!--startprint-->"; //设置打印开始区域
    // var eprnstr="<!--endprint-->";//设置打印结束区域
    // var prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr));//从开始代码向后取html
    // var prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//从结束代码向前取html
    // document.body.innerHTML=prnhtml;
    // window.print();
    // // document.body.innerHTML = bdhtml1;
    // window.reload();
    // return false;
    $("#printImg").print(/*options*/);
}